<template>
  <div class="chartBox">
    <div ref="marketTypeBChart" class="marketTypeBChart"></div>
    <div class="titleRadio">
      <a-checkbox
        v-model:checked="deviationTypeB"
        size="small"
        @change="MarketTypeB"
        >查看偏差</a-checkbox
      >
    </div>
  </div>
</template>
<script setup>



import { TypeBMarket } from "./chartOption"
import { create } from "@/utils/common"
import * as echarts from "echarts"
import { getAllDate } from "@/utils/common"

import moment from "moment"
const $api = inject("$api")
const emits = defineEmits(["update:getMarketLoadinfo"])
const props = defineProps({
  MarketTypeBChartList: {
    type: Object,
    default: () => {},
  },
  handleEmptyTime: {
    type: Function,
  },
  handleLine: {
    type: Function,
  },
  intervalPoints: {
    type: Number,
    default: 24,
  },
  dateRange: {
    type: Array,
    default: () => [],
  },
})
let marketTypeBChart = ref()
const intervalPoints = ref(null)
const MarketTypeBChartList = ref({})
const dateRange = ref([])

watch(
  () => [props.MarketTypeBChartList, props.intervalPoints, props.dateRange],
  async ([val, val2, val3]) => {
    /* MarketPriceinfoList.value = props.props.props.handleEmptyTime(
      JSON.parse(JSON.stringify(val))
    ) */
    if (val && Object.keys(val).length > 0 && val2 && val3) {
      intervalPoints.value = val2
      dateRange.value = val3
      MarketTypeBChartList.value = JSON.parse(JSON.stringify(val))
      props.handleEmptyTime(
        MarketTypeBChartList.value.frontList,
        "loadHourList",
        "loadMinutesList"
      )
      props.handleEmptyTime(
        MarketTypeBChartList.value.actualList,
        "loadHourList",
        "loadMinutesList"
      )
      props.handleEmptyTime(
        MarketTypeBChartList.value.forecastList,
        "loadHourList",
        "loadMinutesList"
      )
      props.handleEmptyTime(
        MarketTypeBChartList.value.deviationshi,
        "loadHourList",
        "loadMinutesList"
      )
      props.handleEmptyTime(
        MarketTypeBChartList.value.deviationri,
        "loadHourList",
        "loadMinutesList"
      )
      await nextTick()
      if (marketTypeBChart.value) {
        MarketTypeB()
      }
    } else {
      MarketTypeBChartList.value = {}
    }
  },
  {
    deep: true,
    immediate: true,
  }
)

let dataList = ref([])
//B类图表

//是否查看偏差
const deviationTypeB = ref(false)
const MarketTypeB = async () => {
  dataList.value = getAllDate(dateRange.value[0], dateRange.value[1])
  if (deviationTypeB.value) {
    marketTypeBChart.value.style.height = 500
    if (TypeBMarket.grid.length === 1) {
      isTypeBDeviation()
    }
  } else {
    noTypeBDeviation()
    marketTypeBChart.value.style.height = 300
  }

  switch (intervalPoints.value) {
    case 24:
      TypeBMarket.xAxis[0].data = create(dataList.value, 60)
      TypeBMarket.series[0].data = props.handleLine(
        MarketTypeBChartList.value.frontList,
        "loadHourList"
      )
      TypeBMarket.series[1].data = props.handleLine(
        MarketTypeBChartList.value.actualList,
        "loadHourList"
      )

      pub2496TypeB(60, "loadHourList")

      break
    case 96:
      TypeBMarket.xAxis[0].data = create(dataList.value, 15)
      TypeBMarket.series[0].data = props.handleLine(
        MarketTypeBChartList.value.frontList,
        "loadMinutesList"
      )
      TypeBMarket.series[1].data = props.handleLine(
        MarketTypeBChartList.value.actualList,
        "loadMinutesList"
      )

      pub2496TypeB(15, "loadMinutesList")
      break
  }
}
//B类24，96公共部分
const pub2496TypeB = (min, field) => {
  if (deviationTypeB.value) {
    TypeBMarket.xAxis[1].data = create(dataList.value, min)
    TypeBMarket.series[2].data = props.handleLine(
      MarketTypeBChartList.value.deviationshi,
      field
    )
    TypeBMarket.series[3].markLine.data = []
    TypeBMarket.series[4].markLine.data = []
    let difference = moment(dateRange.value[1]).diff(
      moment(dateRange.value[0]),
      "day"
    )
    for (let i = 0; i <= difference; i++) {
      if (i !== 0) {
        TypeBMarket.series[3].markLine.data.push({
          xAxis: (TypeBMarket.xAxis[1].data.length / (difference + 1)) * i,
        })
        TypeBMarket.series[4].markLine.data.push({
          xAxis: (TypeBMarket.xAxis[1].data.length / (difference + 1)) * i,
        })
      }
    }
    /* for (let i = 0; i <= 5; i++) {
      if (i !== 0) {
        TypeBMarket.series[3].markLine.data.push({
          xAxis: (TypeBMarket.xAxis[1].data.length / 6) * i - 1,
        });
        TypeBMarket.series[4].markLine.data.push({
          xAxis: (TypeBMarket.xAxis[1].data.length / 6) * i - 1,
        });
      }
    } */
    let tagreObj = TypeBMarket.series.find((item) => item.type === "bar")
    if (tagreObj) {
      let arr = tagreObj.data.filter((item) => item !== "")
      if (arr.length === 0) {
        TypeBMarket.graphic[1].invisible = false
      } else {
        TypeBMarket.graphic[1].invisible = true
      }
    }
  } else {
    TypeBMarket.series[2].markLine.data = []
    let difference = moment(dateRange.value[1]).diff(
      moment(dateRange.value[0]),
      "day"
    )
    for (let i = 0; i <= difference; i++) {
      if (i !== 0) {
        TypeBMarket.series[2].markLine.data.push({
          xAxis: (TypeBMarket.xAxis[0].data.length / (difference + 1)) * i,
        })
      }
    }
    /* for (let i = 0; i <= 5; i++) {
      if (i !== 0) {
        TypeBMarket.series[2].markLine.data.push({
          xAxis: (TypeBMarket.xAxis[0].data.length / 6) * i - 1,
        });
      }
    } */
    TypeBMarket.graphic[1].invisible = true
  }
  var chart = echarts.init(marketTypeBChart.value)
  chart.resize()
  chart.clear()
  chart.setOption(TypeBMarket)
}
//查看B类偏差
const isTypeBDeviation = () => {
  TypeBMarket.grid = [
    {
      height: "28%",
      right: "2%",
      left: "6%",
      top: "15%",
    },
    {
      height: "30%",
      right: "2%",
      left: "6%",
      bottom: "14%",
    },
  ]
  TypeBMarket.xAxis = [
    {
      show: false, //隐藏了x轴
      type: "category",
      gridIndex: 0, //对应前面grid的索引位置（第一个）
      axisTick: {
        show: false,
      },
      axisLabel: {
        formatter: (
          value //X轴的内容
        ) => {
          let ret = "" //拼接加\n返回的类目项
          let max = 10 //每行显示的文字字数
          let val = value.length //X轴内容的文字字数
          let rowN = Math.ceil(val / max) //需要换的行数
          if (rowN > 1) {
            //判断 如果字数大于2就换行
            for (let i = 0; i < rowN; i++) {
              let temp = "" //每次截取的字符串
              let start = i * max //开始截取的位置
              let end = start + max //结束截取的位置
              temp = value.substring(start, end) + "\n"
              ret += temp //最终的字符串
            }
            return ret
          } else {
            return value
          }
        },
      },
      axisPointer: {
        // show: false
      },

      data: [],
    },
    {
      show: true, //隐藏了x轴
      type: "category",
      gridIndex: 1, //对应前面grid的索引位置（第二个）
      axisTick: {
        show: false,
      },
      axisLabel: {
        formatter: (
          value //X轴的内容
        ) => {
          let ret = "" //拼接加\n返回的类目项
          let max = 10 //每行显示的文字字数
          let val = value.length //X轴内容的文字字数
          let rowN = Math.ceil(val / max) //需要换的行数
          if (rowN > 1) {
            //判断 如果字数大于2就换行
            for (let i = 0; i < rowN; i++) {
              let temp = "" //每次截取的字符串
              let start = i * max //开始截取的位置
              let end = start + max //结束截取的位置
              temp = value.substring(start, end) + "\n"
              ret += temp //最终的字符串
            }
            return ret
          } else {
            return value
          }
        },
      },

      data: [],
    },
  ]
  TypeBMarket.yAxis = [
    {
      type: "value",
      gridIndex: 0,
      name: "出力（MW）",
      nameTextStyle: {
        padding: [0, 0, 10, 0],
        fontSize: 13, //y轴坐标轴上title字体大小
        fontWeight: "bold",
        color: "#fff",
      },
      position: "left",
      // nameLocation: "middle",
      splitLine: {
        lineStyle: {
          color: ["#666"],
          type: "solid", //虚线
        },
        show: true,
      },
      //nameLocation: 'start',//y轴name的位置
      //inverse: true,
      axisLine: {
        show: false,
      },
      axisLabel: {
        formatter: "{value}",
        fontSize: 12, //y轴坐标轴上的字体大小
      },
    },
    {
      type: "value",
      gridIndex: 1,
      // nameLocation: "middle",
      name: "偏差（MW）",
      nameTextStyle: {
        padding: [0, 0, 10, 0],
        fontSize: 13, //y轴坐标轴上title字体大小
        fontWeight: "bold",
        color: "#fff",
      },
      splitLine: {
        lineStyle: {
          color: ["#666"],
          type: "solid", //虚线
        },
        show: true,
      },
      position: "left",
      axisLine: {
        show: false,
      },
      axisLabel: {
        formatter: "{value}",
      },
    },
  ]
  TypeBMarket.series.splice(2, 0, {
    name: "偏差量",
    type: "bar",
    xAxisIndex: 1,
    yAxisIndex: 1,
    data: [],
    itemStyle: {
      color: function (params) {
        let colorList = ["#C96771", "#7EB889"]
        let index = params.data > 0 ? 0 : 1
        return colorList[index]
      },
    },
  })
  TypeBMarket.series.push({
    type: "line",
    xAxisIndex: 1,
    yAxisIndex: 1,
    data: [],
    markLine: {
      symbol: ["none", "none"],
      label: { show: false },
      lineStyle: {
        color: "#666",
      },
      emphasis: {
        disabled: true,
      },
      data: [],
    },
  })
}
//不查看B类偏差
const noTypeBDeviation = () => {
  TypeBMarket.grid = TypeBMarket.grid.splice(-1, 1)
  TypeBMarket.grid[0] = {
    top: "17%",
    right: "2%",
    left: "6%",
    bottom: "15%",
  }
  TypeBMarket.xAxis = TypeBMarket.xAxis.filter((item) => item.gridIndex !== 1)
  TypeBMarket.xAxis[0].show = true
  TypeBMarket.yAxis = TypeBMarket.yAxis.filter((item) => item.gridIndex !== 1)
  TypeBMarket.series = TypeBMarket.series.filter(
    (item) => item.xAxisIndex !== 1 && item.yAxisIndex !== 1
  )
}
const updateChart = () => {
  emits("update:getMarketLoadinfo")
}
onMounted(async () => {})
</script>
<style lang="less" scoped>
.chartBox {
  position: relative;
  .marketTypeBChart {
    height: 500px;
    width: 100%;
  }
  .titleRadio {
    position: absolute;
    top: 0;
    right: 0;
  }
  .deviationTypeBox {
    position: absolute;
    right: 2%;
    top: 50%;
    transform: translateY(-50%);
    z-index: 2;
  }
}
</style>
